import config from '../upload/config'
// development 模式下修改html
export default () => {
  return {
    name: 'html-transform',
    transformIndexHtml(html) {
      if(process.env.NODE_ENV==='production'){
        html = prodTransformFontsize(html);
      }else{
        html = devTransformViewport(html);
      }
      // beacon & 007 inject
      html = html.replace('<!-- beacon & 007 inject -->',`<script src="https://mat1.gtimg.com/www/js/emonitor/custom_e439ff7f.js"></script>
    <script>
      // 007初始化代码
      var emonitor007Ins = emonitor.create({
          name: '${config.projectName}',
          mode: '007', // 设置成pecker时上报到啄木鸟
          atta: {
              name: 'newsDesign' //当上报到007时才需要设置该项
          }
      });
    </script>`);
      return html;
    }
  }
}
// 生产模式下 注入fontsize 适配代码
function prodTransformFontsize(html:string){
  return html.replace(
    /<head\s*>/,
    `<head>
  <script>
  (function(){
    //debug
    if(/^(10\.|localhost|127\.|192\.)/.test(location.hostname)||location.search.indexOf('__debug__')>=0){
      var script = document.createElement('script');
      script.charset="UTF-8";
      script.src = "//mat1.gtimg.com/qqcdn/qqnews_design/20210521_oath/vconsole.min.js";
      script.onload=function(){
        if(navigator.platform.search(/^(Mac|Win)/)<0) new VConsole();
      };
      document.head.appendChild(script);
    }
    //fontSize
    var initFontSize = parseFloat(window.getComputedStyle(document.documentElement)['font-size']);
    function setFontSize(isFirst){
      if(/huawei|wxwork/i.test(navigator.userAgent)){
        var screen_width = document.documentElement.clientWidth;
        if (!screen_width) {
            /*qq中有几率为0*/
            setTimeout(setFontSize, 50);
            return;
        }
        var screen_height = window.innerHeight;
        if (window.innerWidth !== screen_width) {
            screen_height *= screen_width / window.innerWidth;
        }
        var fontSize = screen_width / 10;
        document.documentElement.style.fontSize = \`\${fontSize/initFontSize*100}%\`;
      }
    }
    window.addEventListener('load',function(){
      setTimeout(setFontSize,300);
    });
    //auto-scale style
    document.addEventListener('DOMContentLoaded',()=>{
      var style = document.createElement('style');
      window.autoScale = Math.min(1,750/1333/(window.innerWidth/window.innerHeight));
      style.innerHTML=\`.auto-scale{transform:scale(\${window.autoScale});}\`;
      document.head.append(style);
    });
  })();
  </script>
  <style>
    html,body{
      position: relative;
      height: 100%;
      font-size: 10vw;
      margin: 0;
    }
    body{
      font-size: medium;
    }
  </style>`
  )
}
// dev模式下 注入viewport 适配代码
function devTransformViewport(html:string){
  return html.replace(
    /<meta name="viewport"[^\>]+/,
    `<meta name="viewport" content="width=device-width"/>
<script src="//mat1.gtimg.com/qqcdn/qqnews_design/20210521_oath/vconsole.min.js"></script>
<script>
(${consoleProxy.toString()})();
  (()=>{
    //debug
    if(navigator.platform.search(/^(Mac|Win)/)<0) new VConsole();
    //fontSize
    const scale = window.innerWidth/750;
    const meta = document.createElement('meta');
    meta.setAttribute('name',"viewport");
    meta.setAttribute('content',\`width=device-width, initial-scale=\${scale}, maximum-scale=\${scale}, user-scalable=0\`);
    document.head.append(meta);
    window.devicePixelRatio = 1;
    const style = document.createElement('style');
    style.innerHTML=\`html,body{position: relative;height: 100%;margin: 0;}body{font-size: \${100/scale}%;}#__vconsole *{font-size:calc(100vw / 750 * 24) !important!}\`;
    document.head.append(style);
    //auto-scale style
    document.addEventListener('DOMContentLoaded',()=>{
      const style = document.createElement('style');
      window.autoScale = Math.min(1,750/1333/(window.innerWidth/window.innerHeight));
      style.innerHTML=\`.auto-scale{transform:scale(\${window.autoScale});}\`;
      document.head.append(style);
    });
  })();
</script`
  )
}
//run dev 下修改console.log 用来支持直接渲染 canvas
function consoleProxy(){
  const SCALE = 1/5;
  console.log = new Proxy(console.log,{
      apply(target, thisArg, argumentsList){
          const canvasList = [];
          const imageList = [];
          argumentsList.forEach(arg=>{
              if(arg instanceof HTMLCanvasElement){
                  canvasList.push(arg);
              }else if(arg instanceof HTMLImageElement){
                  imageList.push(arg);
              }
          })
          if(canvasList.length){
              console.group(...argumentsList);
              canvasList.forEach(canvas=>{
                  target.call(thisArg,"%c ", `font-size:0;border:1px solid rgba(128,128,128,.15);padding:${canvas.height*SCALE}px ${canvas.width*SCALE}px;background:url('${canvas.toDataURL()}') no-repeat;background-size:100% 100%;`);
              });
              imageList.forEach(image=>{
                  target.call(thisArg,"%c ", `font-size:0;border:1px solid rgba(128,128,128,.15);padding:${image.naturalHeight*SCALE}px ${image.naturalWidth*SCALE}px;background:url('${image.src}') no-repeat;background-size:100% 100%;`);
              });
              return console.groupEnd();
          }else if(imageList.length){
              console.groupCollapsed(...argumentsList);
              imageList.forEach(image=>{
                  target.call(thisArg,"%c ", `font-size:0;border:1px solid rgba(128,128,128,.15);padding:${image.naturalHeight*SCALE}px ${image.naturalWidth*SCALE}px;background:url('${image.src}') no-repeat;background-size:100% 100%;`);
              });
              return console.groupEnd();
          }
          return target.apply(thisArg,argumentsList);
      }
  });
}